package com.ycb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ycb.common.Result;
import com.ycb.dto.SetmealDto;
import com.ycb.exception.CustomException;
import com.ycb.pojo.Category;
import com.ycb.pojo.Setmeal;
import com.ycb.mapper.SetmealMapper;
import com.ycb.pojo.SetmealDish;
import com.ycb.service.ICategoryService;
import com.ycb.service.ISetmealDishService;
import com.ycb.service.ISetmealService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 套餐 服务实现类
 * </p>
 *
 * @author ycb
 * @since 2024-09-30
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements ISetmealService {
    public static List<Category> CATEGORIES;

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private ISetmealDishService setmealDishService;

    @Override
    public List<Setmeal> findListByCategoryId(Long id) {
        if (id == null) {
            return new ArrayList<>();
        }
        QueryWrapper<Setmeal> setmealQueryWrapper = new QueryWrapper<>();
        setmealQueryWrapper.eq("category_id",id);
        List<Setmeal> list = this.list(setmealQueryWrapper);
        return list;
    }

    @Override
    public long findCountByCategoryId(Long id) {
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        return this.count(setmealLambdaQueryWrapper);
    }

    @Override
    public Result<Page> pageSetmealDto(int page, int pageSize, String name) {
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<>();
        //构造条件构造器
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件（当我们没有输入name时，就相当于查询所有了）
        setmealLambdaQueryWrapper.like(!(name == null || "".equals(name)), Setmeal::getName, name);
        //并对查询的结果进行降序排序，根据更新时间
        setmealLambdaQueryWrapper.orderByDesc(Setmeal::getUpdateTime);
        this.page(setmealPage,setmealLambdaQueryWrapper);

        //复制dish的信息
        BeanUtils.copyProperties(setmealPage,setmealDtoPage,"records");
        List<Setmeal> records = setmealPage.getRecords();
        List<SetmealDto> setmealDtos = setmeal2Dto(records);
        setmealDtoPage.setRecords(setmealDtos);
        return Result.success(setmealDtoPage);
    }

    /**
     * setmealList 转换为 setmealDtoList
     * @param setmealList
     * @return
     */
    public List<SetmealDto> setmeal2Dto(List<Setmeal> setmealList){
        //查询菜品分类信息
        if (CATEGORIES ==null || CATEGORIES.isEmpty()) {
            CATEGORIES = categoryService.listByType(2);
        }

        Map<Long, List<Category>> collect = CATEGORIES.stream().collect(Collectors.groupingBy(Category::getId));

        List<SetmealDto> setmealDtos = new ArrayList<>();
        for (Setmeal record : setmealList) {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(record,setmealDto);
            List<Category> categories = collect.get(setmealDto.getCategoryId());
            if (categories != null && !categories.isEmpty()) {
                setmealDto.setCategoryName(categories.get(0).getName());
            }
            setmealDtos.add(setmealDto);
        }
        return setmealDtos;
    }

    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        this.save(setmealDto);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
        }
        setmealDishService.saveBatch(setmealDishes);
    }

    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        //删除套餐中的菜品信息
        QueryWrapper<SetmealDish> setmealDishQueryWrapper = new QueryWrapper<>();
        setmealDishQueryWrapper.in("setmeal_id",ids);
        setmealDishService.remove(setmealDishQueryWrapper);
        this.removeBatchByIds(ids);
    }

    @Override
    public SetmealDto getDtoById(Long id) {
        Setmeal setmeal = this.getById(id);
        if (setmeal == null) {
            throw new CustomException("套餐信息不存在，请刷新重试");
        }
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal, setmealDto);
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> setmealDishes = setmealDishService.list(queryWrapper);
        setmealDto.setSetmealDishes(setmealDishes);
        return setmealDto;
    }

    @Override
    @Transactional
    public void updateWithDish(SetmealDto setmealDto) {

        Long setmealId = setmealDto.getId();
        //先根据id把setmealDish表中对应套餐的数据删了
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId,setmealId);
        setmealDishService.remove(queryWrapper);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        if (setmealDishes != null) {
            for (SetmealDish setmealDish : setmealDishes) {
                setmealDish.setSetmealId(setmealId);
            }
            //更新套餐对应菜品数据
            setmealDishService.saveBatch(setmealDishes);
        }

        //更新套餐数据
        this.updateById(setmealDto);

    }
}
